
// 封装栈类
function Stack() {
  this.items = [];
  Stack.prototype.push = (element) => this.items.push(element);
  Stack.prototype.pop = () => this.items.pop();
  Stack.prototype.peek = () => this.items[this.items.length - 1];
  Stack.prototype.size = () => this.items.length;
  Stack.prototype.isEmpty = () => !this.items.length
  Stack.prototype.toString = () => {
    let resultString = "";
    for (let i = 0; i < this.items.length; i++) {
      resultString += this.items[i] + " ";
    }
    return resultString;
  };
}

// 十进制转换二进制
// decNumber: 10进制值
function Dec2Bin(decNumber) {
  // 1. new一个栈对象
  const stack = new Stack();

  // 2. 循环操作
  while (decNumber > 0) {
    // 2.1. 获取余数, 压入栈
    stack.push(decNumber % 2);

    // 2.2. 获取整除后的结构, 作为下一次运算的数字
    decNumber = Math.floor(decNumber / 2);
  }

  // 3. 循环结束了 栈中应该有许多 010101 的二进制数据了 依次从栈顶弹出即可
  let binaryString = "";
  while (!stack.isEmpty()) {
    binaryString += stack.pop();
  }

  return binaryString;
}

console.log(Dec2Bin(100));
console.log(Dec2Bin(1000));
console.log(Dec2Bin(10));
